<template>
  <!-- 辖区管理 -- 新增/编辑 -->
  <div>
    <public-modal
      width="600px"
      :footer="false"
      :title="title"
      :publicVisible="publicVisible"
      @handleOk="handleOk"
      @cancel="cancel"
    >
      <div slot="content">
        <a-form-model
          :model="form"
          :rules="rules"
          ref="form"
          class="formStyle"
          autocomplete="off"
          layout="inline"
          :labelCol="{ style: 'width: 100px' }"
        >
          <a-form-model-item label="辖区编码" prop="jurisdictionNo">
            <a-input
              :maxLength="30"
              autocomplete="off"
              id="warning"
              placeholder="请填写辖区编码"
              v-model="form.jurisdictionNo"
            />
          </a-form-model-item>

          <a-row :gutter="24">
            <a-col :span="24">
              <a-form-model-item label="辖区名称" prop="jurisdictionName" :required="true">
                <a-input
                  :maxLength="30"
                  autocomplete="off"
                  id="warning"
                  placeholder="请填写辖区名称"
                  v-model="form.jurisdictionName"
                />
              </a-form-model-item>
            </a-col>
          </a-row>

          <a-row :gutter="24">
            <a-col :span="24">
              <a-form-item label="辖区颜色">
                <div class="colorSel">
                  <div
                    v-for="(item, i) in colSel"
                    :key="i"
                    class="colorBlock"
                    :class="item == positionColour ? 'bigSel' : ''"
                    :style="{ background: item }"
                    @click="pitchOnHandle(item)"
                  ></div>
                </div>
                <div class="colorSel_err" v-if="pleaseFlag">请选择!</div>
              </a-form-item>
            </a-col>
          </a-row>

          <a-row :gutter="4">
            <a-col :span="22">
              <a-form-item label="经度" prop="lng">
                <a-input :maxLength="30" autocomplete="off" placeholder="例如104.123456" v-model="form.lng" />
              </a-form-item>
            </a-col>
            <a-col :span="2">
              <img
                @click="showMap"
                class="select-map-img cursor"
                style="width: 36px; height: 36px"
                src="@/assets/imgs/in-map.png"
              />
            </a-col>
          </a-row>

          <a-row :gutter="24">
            <a-col :span="24">
              <a-form-item label="纬度" prop="lat">
                <a-input :maxLength="30" autocomplete="off" placeholder="例如34.865432" v-model="form.lat" />
              </a-form-item>
            </a-col>
          </a-row>

          <a-row :gutter="4">
            <a-col :span="22">
              <a-form-item label="边界" prop="areaPosition">
                <a-input
                  placeholder="例：lat:104.123456,lng:34.78908"
                  :maxLength="30"
                  autocomplete="off"
                  v-model="form.areaPosition"
                />
              </a-form-item>
            </a-col>
            <a-col :span="2">
              <img
                @click="createBorderLine"
                class="select-map-img cursor"
                style="width: 36px; height: 36px"
                src="@/assets/imgs/map-area.png"
              />
            </a-col>
          </a-row>

          <a-row :gutter="24" class="textarea">
            <a-col :span="24">
              <a-form-model-item label="范围描述" prop="scopeDescription">
                <a-textarea :maxLength="50" placeholder="请填写范围描述" v-model="form.scopeDescription" />
              </a-form-model-item>
            </a-col>
          </a-row>

          <a-row :gutter="24" class="row-fitem" style="margin-top: 0.2rem">
            <a-col :span="24">
              <a-form-model-item label="辖区民警" prop="principalPoliceUserIdList">
                <a-checkbox
                  :indeterminate="indeterminate"
                  :checked="checkAll"
                  @change="onCheckAllChange"
                  class="select-all-style"
                >
                  全选
                </a-checkbox>
                <a-checkbox-group
                  class="area-checkbox-group"
                  name="principalPoliceUserIdList"
                  v-model="form.principalPoliceUserIdList"
                  :options="policeUserOpt"
                  @change="onChange"
                  v-if="policeUserOpt.length"
                />
                <p v-else>请为派出所添加民警</p>
              </a-form-model-item>
            </a-col>
          </a-row>
          <a-row :gutter="24" class="row-fitem" style="margin-top: 0.1rem">
            <a-col :span="24">
              <a-form-model-item label="责任民警" prop="principalPoliceUserId">
                <a-radio-group
                  name="radioGroup"
                  v-model="form.principalPoliceUserId"
                  @change="onRadioChange"
                  v-if="policeRadioList.length"
                >
                  <a-radio v-for="(item, index) in policeRadioList" :key="index" :value="item.value">
                    {{ item.label }}
                  </a-radio>
                </a-radio-group>
                <p v-if="policeUserOpt.length && !policeRadioList.length">请选择辖区民警</p>
                <p v-if="!policeUserOpt.length">请为派出所添加民警</p>
              </a-form-model-item>
            </a-col>
          </a-row>

          <a-row :gutter="24" class="row-fitem" style="margin-top: 0.1rem">
            <a-col :span="24">
              <a-form-model-item label="辖区辅警" prop="principalAuxiliaryUserIdList">
                <a-checkbox
                  :indeterminate="auxiliaryIndeterminate"
                  :checked="auxiliaryCheckAll"
                  @change="onCheckAllChangeAuxiliary"
                  class="select-all-style"
                >
                  全选
                </a-checkbox>
                <a-checkbox-group
                  class="area-checkbox-group"
                  name="principalAuxiliaryUserIdList"
                  v-model="form.principalAuxiliaryUserIdList"
                  :options="auxiliaryPolice"
                  v-if="auxiliaryPolice.length"
                />
                <p v-else>请为派出所添加辅警</p>
              </a-form-model-item>
            </a-col>
          </a-row>
          <a-row :gutter="24" class="row-fitem" style="margin-top: 0.1rem">
            <a-col :span="24">
              <a-form-model-item label="网格员" prop="principalGridUserIdList">
                <a-checkbox
                  :indeterminate="indeterminateGrid"
                  :checked="checkAllGrid"
                  @change="onCheckAllChangeGrid"
                  class="select-all-style"
                >
                  全选
                </a-checkbox>
                <a-checkbox-group
                  class="area-checkbox-group"
                  name="principalGridUserIdList"
                  v-model="form.principalGridUserIdList"
                  :options="gridOperator"
                  v-if="gridOperator.length"
                />
                <p v-else>请为派出所添加网格员</p>
              </a-form-model-item>
            </a-col>
          </a-row>
        </a-form-model>
      </div>
    </public-modal>
    <t-map
      :visible.sync="isShowMap"
      :renderType="renderType"
      @border="getBorder"
      @getLatLong="getLatLong"
      ref="tMap"
    ></t-map>
  </div>
</template>

<script>
import { jurisdictionAdd, jurisdictionEdit } from '@/api/area'
import { findPoliceAgencyList } from '@/api/police'
import { commitTrim } from '@/utils/util'
import publicModal from '@/components/publicModal'
import TMap from '@/components/t-map4showPolyon/index.vue'
import { findAuxiliaryUserList, findGridUserList } from '../../../api/police'
// import TMapPolyon from '@/components/t-map4showPolyon/index.vue'

export default {
  components: { publicModal, TMap },
  props: {
    title: {
      type: String,
      default: '',
    },
  },
  data() {
    let vaildUserId = (rule, value, callback) => {
      if ((value === '' || !value) && this.policeRadioList.length) {
        callback(new Error('请选择辖区责任民警'))
      } else {
        callback()
      }
    }

    return {
      // form: this.$form.createForm(this),
      form: {},
      records: {},
      publicVisible: false,
      // 民警
      policeUserOpt: [],
      // 辅警
      auxiliaryPolice: [],
      // 网格员
      gridOperator: [],
      policeRadioList: [],
      rules: {
        jurisdictionNo: [{ validator: this.validateJurisdiction, trigger: 'blur' }],
        jurisdictionName: [{ required: true, message: '请填写辖区名称' }],
        lng: [{ required: true, message: '请输入经度' }],
        lat: [{ required: true, message: '请输入纬度' }],
        areaPosition: [{ required: true, message: '请输入纬度' }],
        principalPoliceUserId: [{ required: true, validator: vaildUserId, trigger: 'change' }],
        principalPoliceUserIdList: [{ required: true, message: '请选择辖区民警', trigger: 'change' }],
        principalAuxiliaryUserIdList: [{ required: false, message: '请选择辖区辅警', trigger: 'change' }],
        principalGridUserIdList: [{ required: false, message: '请选择辖区网格员', trigger: 'change' }],
      },
      positionColour: '',
      pleaseFlag: false,
      colSel: [
        'rgba(255, 27, 1)',
        'rgba(255, 153, 1)',
        'rgba(255, 238, 1)',
        'rgba(1, 255, 102)',
        'rgba(20, 255, 239)',
        'rgba(0, 64, 254)',
        'rgba(146, 0, 255)',
      ],
      isShowMap: false,
      renderType: '',
      indeterminate: false,
      checkAll: false,
      auxiliaryIndeterminate: false,
      auxiliaryCheckAll: false,
      indeterminateGrid: false,
      checkAllGrid: false,
    }
  },
  methods: {
    show(records) {
      this.records = records
      this.positionColour = ''
      this.pleaseFlag = false
      this.publicVisible = true
      this.getClassify()

      this.policeRadioList = []
      this.$set(this.form, 'principalPoliceUserIdList', [])
      this.$set(this.form, 'principalPoliceUserId', null)

      // 编辑
      if (records && records.id) {
        this.$set(this, 'form', Object.assign({}, records))
        this.positionColour = records.positionColour
        let policeUserList = records.principalPoliceUserList
        if (policeUserList && policeUserList.length) {
          this.form.principalPoliceUserIdList = policeUserList.map((v) => {
            this.onChange(v.id)
            return v.id
          })

          this.form.principalPoliceUserId = this.records.principalPoliceUser.id
          setTimeout(() => {
            this.onChange(this.form.principalPoliceUserIdList)
          }, 1000)
        }
        // 如果有辖区辅警和网格员，对其进行赋值
        // principalGridUserIdList
        // principalAuxiliaryUserIdList
        const { auxiliaryUserInfoList, gridUserInfoList } = records
        // 辅警
        if (auxiliaryUserInfoList && auxiliaryUserInfoList.length) {
          const principalAuxiliaryUserIdListIds = auxiliaryUserInfoList.map((item) => item.id)
          this.$set(this.form, 'principalAuxiliaryUserIdList', principalAuxiliaryUserIdListIds)
          // 控制全选还是 否全
        }
        // 网格员
        if (gridUserInfoList && gridUserInfoList.length) {
          const principalGridUserIdListIds = gridUserInfoList.map((item) => item.id)
          this.$set(this.form, 'principalGridUserIdList', principalGridUserIdListIds)
        }
      }
    },

    validateJurisdiction(rule, value, callback) {
      if (!value || new RegExp(/^[0-9a-zA-Z]*$/).test(value)) {
        callback()
      } else {
        callback('请输入数字或字母!')
      }
    },

    // ! 地图方法开始
    showMap() {
      this.renderType = 'point'
      this.isShowMap = true
    },
    getLatLong(value) {
      this.form.lng = value[0]
      this.form.lat = value[1]
    },
    getBorder(value) {
      this.form.areaPosition = value
    },
    createBorderLine() {
      this.$refs.tMap.borderLine = true
      // 绘制 边界
      this.renderType = 'boundary'
      this.$refs.tMap.borderStr = this.form.areaPosition
      this.isShowMap = true
    },
    // ! 地图方法结束

    pitchOnHandle(item) {
      this.positionColour = item
      this.pleaseFlag = false
    },

    onChange(checkedList) {
      this.policeRadioList = []
      for (let i = 0; i < this.policeUserOpt.length; i++) {
        for (let j = 0; j < checkedList.length; j++) {
          if (this.policeUserOpt[i].value == checkedList[j]) {
            this.policeRadioList.push(this.policeUserOpt[i])
          }
        }
      }

      if (!checkedList.length) {
        this.$set(this.form, 'principalPoliceUserId', null)
      } else if (checkedList && !this.form.principalPoliceUserId) {
        this.$set(this.form, 'principalPoliceUserId', null)
      } else if (checkedList.indexOf(this.form.principalPoliceUserId) == -1) {
        this.form.principalPoliceUserId = null
      }

      this.indeterminate = !!checkedList.length && checkedList.length < this.policeUserOpt.length
      this.checkAll = checkedList.length === this.policeUserOpt.length
    },
    onRadioChange(e) {
      console.log(e.target, 'ee')
    },

    handleOk() {
      let flag
      this.$refs.form.validate((valid) => {
        flag = valid
      })

      if (!flag) {
        return false
      }

      if (!this.positionColour) {
        this.pleaseFlag = true
        return
      }

      commitTrim(this.form)
      let data = {
        policeAgencyId: this.records.policeAgencyId,
        ...this.form,
        positionColour: this.positionColour,
      }

      if (!this.records.id) {
        jurisdictionAdd(data).then((res) => {
          this.$message.success(res.message)
          this.cancel()
          this.$emit('refresh')
        })
      } else {
        jurisdictionEdit({ id: this.records.id, ...data }).then((res) => {
          this.$message.success(res.message)
          this.cancel()
          this.$emit('refresh')
        })
      }
    },
    cancel() {
      this.publicVisible = false
      this.indeterminate = false
      this.checkAll = false

      this.indeterminateGrid = false
      this.checkAllGrid = false
      this.auxiliaryIndeterminate = false
      this.auxiliaryCheckAll = false
      this.form = {}
    },
    getClassify() {
      this.policeUserOpt = []
      // 获取民警
      findPoliceAgencyList({ policeAgencyId: this.records.policeAgencyId }).then((res) => {
        if (res.result.length) {
          this.policeUserOpt = res.result.map((v) => ({
            label: v.userName,
            value: v.id,
          }))
        }
      })
      // 获取辅警
      findAuxiliaryUserList({ policeAgencyId: this.records.policeAgencyId }).then((res) => {
        if (res.result.length) {
          this.auxiliaryPolice = res.result.map((v) => ({
            label: v.userName,
            value: v.id,
          }))
          this.auxiliaryIndeterminate =
            !!this.form.principalAuxiliaryUserIdList.length &&
            this.form.principalAuxiliaryUserIdList.length < this.auxiliaryPolice.length
          this.auxiliaryCheckAll = this.form.principalAuxiliaryUserIdList.length === this.auxiliaryPolice.length
        }
      })
      // 网格员
      findGridUserList({ policeAgencyId: this.records.policeAgencyId }).then((res) => {
        if (res.result.length) {
          this.gridOperator = res.result.map((v) => ({
            label: v.userName,
            value: v.id,
          }))
          this.indeterminateGrid =
            !!this.form.principalGridUserIdList.length &&
            this.form.principalGridUserIdList.length < this.gridOperator.length
          this.checkAllGrid = this.form.principalGridUserIdList.length === this.gridOperator.length
        }
      })
    },
    onCheckAllChange(e) {
      this.form.principalPoliceUserIdList = e.target.checked ? this.policeUserOpt.map((item) => item.value) : []
      // 全选的时候
      if (e.target.checked) {
        this.onChange(this.form.principalPoliceUserIdList)
      } else {
        this.onChange([])
      }
      this.indeterminate = false
      this.checkAll = e.target.checked
    },
    onCheckAllChangeAuxiliary(e) {
      this.form.principalAuxiliaryUserIdList = e.target.checked ? this.auxiliaryPolice.map((item) => item.value) : []

      this.auxiliaryIndeterminate = false
      this.auxiliaryCheckAll = e.target.checked
    },
    onCheckAllChangeGrid(e) {
      this.form.principalGridUserIdList = e.target.checked ? this.gridOperator.map((item) => item.value) : []
      this.indeterminateGrid = false
      this.checkAllGrid = e.target.checked
    },
  },
}
</script>

<style scoped lang="less">
.select-all-style {
  & > :nth-child(2) {
    font-weight: bold;
    color: #1163b8;
    margin-left: -6px;
  }
}
.textarea {
  //   margin-bottom: 0.15rem;
  height: 0.6rem;
  .ant-input {
    resize: none;
    max-height: 0.6rem;
    min-height: 0.6rem;
  }
}

.row-fitem {
  /deep/.ant-col {
    height: 100%;
  }

  /deep/.ant-checkbox-group {
    label {
      margin-bottom: 0.1rem;
      font-weight: bold;
      color: #1163b8;
    }
  }

  /deep/.ant-radio-group {
    label {
      margin-bottom: 0.1rem;
      font-weight: bold;
      color: #1163b8;
    }
  }

  p {
    font-weight: 500;
    font-size: 0.14rem;
    color: #ff7070;
  }

  span {
    font-weight: 500;
    font-size: 0.14rem;
    color: #ff7070;
  }
}

.colorSel {
  display: flex;
  align-items: flex-end;

  .colorBlock {
    margin: 5px 3px 0;
    border-radius: 4px;
    width: 30px;
    height: 30px;
  }

  .bigSel {
    width: 40px;
    height: 40px;
  }
}
.colorSel_err {
  margin-top: -8px;
  font-size: 14px;
  font-family: PingFang SC;
  font-weight: 500;
  color: #ff5d5d;
}

.area-checkbox-group {
  display: flex;
  flex-wrap: wrap;
  /deep/.ant-checkbox-wrapper {
    width: 25%;
    margin-right: 0;
  }
}
</style>
